﻿/***************************************************************
 *Copyright(c) 2014-2015 Company By LH Unigress
 *All rights reserved.
 *文件名称：前台销售管理头文件
 *简要描述：前台销售管理，加载数据库的商品的信息，根据顾客的消费进行相应的结账操作
 *
 *当前版本：V3.0
 *作者：Kelvin Li
 *创作日期：2015/07
 *Email:creazylq@163.com
 *说明：主要用于显示顾客购买商品的细节显示，顾客购买商品后对数据库中数据进行相应的修改
******************************************************************/
#include "salewidget.h"
#include "constvalue.h"
#include "basicdatawidget.h"
#include "myapp.h"
#include "myhelper.h"
#include "paywidget.h"
#include "serverhelp.h"
#include "sqlhelp.h"
#include "ui_salewidget.h"
#include "commonhelper.h"
#include "pickonedlg.h"
#include "modifyitemdlg.h"

#include <QCompleter>
#include <QCursor>
#include <QDebug>
#include <QKeyEvent>
#include <QModelIndex>
#include <QSqlError>
#include <QSqlQuery>
#include <QStringListModel>
#include <QTimer>
#include <QSqlTableModel>

SaleWidget::SaleWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::SaleWidget)
{
    m_viewHeaderList << "款台号" << "商品编码" << "商品条码" << "商品简称" << "应收价"
                     << "减免" << "实收价" << "数量" << "单位" << "总价" << "营业员" << "创建时间" << "备注";
    ui->setupUi(this);

    this->initForm();
    this->initParameters();
    this->createConnection();
    this->updateTableview();
}

SaleWidget::~SaleWidget()
{
    delete ui;
}

void SaleWidget::initForm()
{
    setMouseTracking(true);
    //设置鼠标样式
    mouseCursor = new QCursor(QPixmap(DEFAULT_CURSOR), 15, 10);
    this->setCursor(*mouseCursor);

    m_pBasicWidget = new BasicDataWidget();
    m_psqlhelp = new SqlHelp();
    m_pPaywidget = new PayWidget();
    m_pPickOne = new PickOneDlg(this);
}

void SaleWidget::initParameters()
{
    QString today_now("当前时间：");
    today_now += QDate::currentDate().toString(Qt::ISODate);
    today_now += " ";
    today_now += QTime::currentTime().toString();
    ui->label_todayAndNow->setText(today_now);
    startTimer(1000);

    ui->cobUser->addItem(Myapp::CurrentUserName);
    this->setFocusPolicy(Qt::StrongFocus);
    ui->lineEdit_goodsSearch->setFocus();

    m_tableModel = new QSqlTableModel(this);
    m_tableModel->setTable("selling");
    m_tableModel->setEditStrategy(QSqlTableModel::OnFieldChange);
    ui->tableView->setModel(m_tableModel);
    ui->tableView->hideColumn(0);
    this->summarizeGoods();
}

void SaleWidget::createConnection()
{
    connect(m_pPaywidget, &PayWidget::confirmPayment, this, &SaleWidget::on_ConfirmPayment);
    connect(m_pPickOne, &PickOneDlg::picked, this, &SaleWidget::on_pickOne);
    connect(ui->tableView, &QTableView::doubleClicked, this, &SaleWidget::on_modifyItem);
    connect(m_tableModel, &QSqlTableModel::dataChanged, this, &SaleWidget::summarizeGoods);
}

void SaleWidget::updateTableview()
{
    m_tableModel->select();
    for (int var = 0; var < m_tableModel->columnCount(); ++var) {
        m_tableModel->setHeaderData(var, Qt::Horizontal, m_viewHeaderList.at(var));
    }
    ui->tableView->resizeColumnsToContents();
    ui->tableView->horizontalHeader()->setStretchLastSection(true);
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows); // 选中整行
}

void SaleWidget::timerEvent(QTimerEvent *e)
{
    Q_UNUSED(e);
    QString today_now("当前时间：");
    today_now += QDate::currentDate().toString(Qt::ISODate);
    today_now += " ";
    today_now += QTime::currentTime().toString();
    ui->label_todayAndNow->setText(today_now);
}

void SaleWidget::on_pbnFindMmeber_clicked()
{
    m_pBasicWidget->SetPbnCheck("VIP");
    m_pBasicWidget->exec();
}

void SaleWidget::on_pickOne(const QString &goodsId)
{
    if (m_psqlhelp->FindIDiSEist("selling", "goodsId", goodsId)) {
        this->increaseQuantity(goodsId);
    } else {
        this->addGoodsToSelling(goodsId);
    }
}

void SaleWidget::on_lineEdit_goodsSearch_textEdited()
{
    m_pPickOne->updateModel(ui->lineEdit_goodsSearch->text());
    m_pPickOne->show();
//    xdebug << ui->lineEdit_goodsSearch->pos();
//    xdebug << ui->lineEdit_goodsSearch->mapToGlobal(ui->lineEdit_goodsSearch->pos());
//    xdebug << ui->groupBox_7->mapToGlobal(ui->lineEdit_goodsSearch->pos());
//    xdebug << ui->lineEdit_goodsSearch->mapToGlobal(QPoint(0, 0));
//    xdebug << this->mapToGlobal(pos());
//    m_pPickOne->move(ui->groupBox_7->mapToGlobal(ui->lineEdit_goodsSearch->pos()) -
//                      QPoint(0, m_pPickOne->frameGeometry().height()));  // 与下句等效，但可理解性差
    m_pPickOne->move(ui->lineEdit_goodsSearch->mapToGlobal(QPoint(0, 0)) -
                      QPoint(0, m_pPickOne->frameGeometry().height()));
}

void SaleWidget::keyPressEvent(QKeyEvent *key)
{
    switch (key->key()) {
    case Qt::Key_Enter:
    case Qt::Key_Return:
        break;
    case Qt::Key_F2:
        break;
    default:
        break;
    }
}

/**
 * @brief SaleWidget::addGoodstoSelling 增加选择的商品到售卖进行表selling
 * @param goodsId
 */
void SaleWidget::addGoodsToSelling(const QString &goodsId)
{
    QSqlQuery query;
    QString goodsName;
    float recPrice = 0.0;
    int quantity = 1;
    float discount = 0.0;
    QString unit;
    QString barCode;

    QString sql = "SELECT g.simpleName, g.sellPrice, gu.unitName, gb.barCode FROM goods AS g, "
                  "goodsUnit AS gu, goodsBarCode AS gb "
                  "WHERE g.id = '%1' and g.units = gu.id and g.id = gb.goodId";
    sql = sql.arg(goodsId);
    xdebug << sql;
    query.exec(sql);
    while (query.next()) {
        goodsName = query.value(0).toString();
        recPrice = query.value(1).toFloat();
        unit = query.value(2).toString();
        barCode = query.value(3).toString();
    }
    myHelper::Sleep(100);

    sql = "INSERT INTO selling (goodsId, goodsBarCode, goodsShortName, recPrice, realPrice, "
          "quantity, unit, totalPrice, salesman) "
          "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";  // 共9列
    query.prepare(sql);
    query.addBindValue(goodsId);
    query.addBindValue(barCode);
    query.addBindValue(goodsName);
    query.addBindValue(recPrice);
    query.addBindValue(recPrice - discount);
    query.addBindValue(quantity);
    query.addBindValue(unit);
    query.addBindValue(recPrice * quantity);
    query.addBindValue(ui->cobUser->currentText());  // 共9
    query.exec();

    myHelper::Sleep(100);

    this->updateTableview();
    this->summarizeGoods();
//    ui->tableView->reset();
}

/**
 * @brief SaleWidget::increaseQuantity 增加售卖进行表selling中相同商品数量，更新相应费用
 * @param goodsId  商品编号
 */
void SaleWidget::increaseQuantity(const QString &goodsId)
{
    int quantity = 0;
    float recPrice = 0.0;
    float discount = 0.0;
    QSqlQuery query;
    QString selectSql = "SELECT recPrice, discount, quantity FROM selling WHERE goodsId = '" + goodsId + "'";
    query.exec(selectSql);
    while (query.next()) {
        recPrice = query.value(0).toFloat();
        discount = query.value(1).toFloat();
        quantity = query.value(2).toInt();
    }

    myHelper::Sleep(100);

    quantity++;
    float totalPrice = quantity * (recPrice - discount);
    QString updateSql = "UPDATE selling SET quantity = %1, totalPrice = %2 WHERE goodsId = '%3'";
    updateSql = updateSql.arg(quantity).arg(totalPrice).arg(goodsId);
    xdebug << "updateSQL: " << updateSql;
    query.exec(updateSql);

    myHelper::Sleep(100);

    this->updateTableview();
    this->summarizeGoods();
//    ui->tableView->reset();
}

/*
 *功能：自动保存销售记录,以便以后进行统计操作
 *说明：检索商品信息后，会自动添加信息至sell_detail表中
*/
void SaleWidget::on_ConfirmPayment()
{
    QString selectSql = "SELECT termId, goodsId, goodsBarCode, goodsShortName, recPrice, discount,"
                        "realPrice, quantity, unit, totalPrice, salesman, notes FROM selling";
    QString inSalesSql = "INSERT INTO sales (serialNo, termId, goodsId, goodsBarCode, goodsShortName,"
                         "recPrice, discount, realPrice, quantity, unit, totalPrice, salesman, notes, payType)"
                         "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    QString inSalesSummarySql = "INSERT INTO sales_summary (termId, serialNo, amount, realPay, change, salesman, notes)"
                                "VALUES (?, ?, ?, ?, ?, ?, ?)";
    QString serialNo = QDate::currentDate().toString("yyMMdd") + QTime::currentTime().toString("HHmmss");
    QString payType = m_pPaywidget->getPayType();
    QString salesman = ui->cobUser->currentText();
    QString termId;
    float amount = 0.0;

    QSqlQuery selectQuery;
    QSqlQuery inSalesQuery;
    QSqlQuery inSalesSummaryQry;
    inSalesQuery.prepare(inSalesSql);
    inSalesSummaryQry.prepare(inSalesSummarySql);
    selectQuery.exec(selectSql);
    while (selectQuery.next()) {
        inSalesQuery.addBindValue(serialNo);
        for (int var = 0; var < 12; ++var) {
            inSalesQuery.addBindValue(selectQuery.value(var));
        }
        inSalesQuery.addBindValue(payType);
        inSalesQuery.exec();
        amount += selectQuery.value(6).toFloat() * selectQuery.value(7).toInt();  // 总价当前所在列6
        termId = selectQuery.value(0).toString();
    }
    inSalesSummaryQry.addBindValue(termId);
    inSalesSummaryQry.addBindValue(serialNo);
    inSalesSummaryQry.addBindValue(amount);
    inSalesSummaryQry.addBindValue(m_pPaywidget->getActuallyPay());
    inSalesSummaryQry.addBindValue(m_pPaywidget->getChange());
    inSalesSummaryQry.addBindValue(salesman);
    QString notes("");
    inSalesSummaryQry.addBindValue(notes);
    inSalesSummaryQry.exec();

    on_pbnClear_clicked();
}

void SaleWidget::summarizeGoods()
{
    QSqlQuery query;
    QString sql = "SELECT SUM(quantity), SUM(totalPrice), SUM(discount * quantity) FROM selling";
    query.exec(sql);
    while (query.next()) {
        ui->labNum->setText("￥ " + query.value(0).toString());
        ui->labelPrice->setText("￥ " + query.value(1).toString());
        ui->labelDiscount->setText("￥" + query.value(2).toString());
    }
}

void SaleWidget::on_pbnClear_clicked()
{
    m_psqlhelp->DeleteTableInfo("selling", "");
    this->updateTableview();
//    ui->tableView->reset();
    ui->lineEdit_goodsSearch->clear();
    summarizeGoods();
}

void SaleWidget::on_pbnRemoveOne_clicked()
{
    QModelIndexList indexList = ui->tableView->selectionModel()->selectedIndexes();
    if (!indexList.isEmpty()) {
        m_tableModel->removeRow(indexList.at(0).row());
    }
    this->updateTableview();
//    ui->tableView->reset();
}

void SaleWidget::on_pbnCheck_clicked()
{
    m_pPaywidget->setCheckInfo(ui->labelPrice->text().mid(1), ui->labelDiscount->text().mid(1));
    m_pPaywidget->exec();
}

void SaleWidget::on_modifyItem(const QModelIndex &index)
{
    float recPrice = m_tableModel->index(index.row(), 4).data().toFloat();   // 应收价列索引当前为4
    float discount = 0.0;
    int quantity = 0;
    QString notes;
    ModifyItemDlg a(this);
    a.setDicount(m_tableModel->index(index.row(), 5).data().toFloat());  // 减免列索引当前为5
    a.setCount(m_tableModel->index(index.row(), 7).data().toInt());      // 数量列索引当前为7
    a.setNotes(m_tableModel->index(index.row(), 12).data().toString());  // 备注列索引当前为12
    if (a.exec()) {
        discount = a.getDicount();
        quantity = a.getCount();
        notes = a.getNotes();

        float realPrice = recPrice - discount;
        float totalPrice = realPrice * quantity;

        m_tableModel->setData(m_tableModel->index(index.row(), 5), discount);   // 减免列索引当前为5
        m_tableModel->setData(m_tableModel->index(index.row(), 6), realPrice);  // 实收价列索引当前为6
        m_tableModel->setData(m_tableModel->index(index.row(), 7), quantity);   // 数量价列索引当前为7
        m_tableModel->setData(m_tableModel->index(index.row(), 9), totalPrice); // 总价列索引当前为9
        m_tableModel->setData(m_tableModel->index(index.row(), 12), notes);     // 备注列索引当前为12
    }
//    this->updateTableview();
    ui->tableView->reset();
}
